#include "data_simulator.h"

// 生成模拟雷达数据
std::vector<std::vector<Pulse>> DataSimulator::generateData(const std::vector<TargetInfo> &targets)
{
    std::vector<std::vector<Pulse>> antenna_data(
        params.num_antennas,
        std::vector<Pulse>(params.num_pulses,
                           Pulse(params.num_samples, Complex(0, 0))));

    // 添加噪声
    for (int ant = 0; ant < params.num_antennas; ++ant)
    {
        for (int pulse = 0; pulse < params.num_pulses; ++pulse)
        {
            for (int sample = 0; sample < params.num_samples; ++sample)
            {
                float real = noise_dist(generator);
                float imag = noise_dist(generator);
                antenna_data[ant][pulse][sample] = Complex(real, imag);
            }
        }
    }

    // 添加目标信号
    for (const auto &target : targets)
    {
        addTarget(antenna_data, target);
    }

    return antenna_data;
}

void DataSimulator::addTarget(std::vector<std::vector<Pulse>> &data, const TargetInfo &target)
{
    // 计算目标参数对应的单元索引
    int range_bin = static_cast<int>(target.range / params.getRangeResolution());
    float doppler_freq = 2.0f * target.velocity * params.carrier_frequency / params.light_speed;
    int doppler_bin = static_cast<int>(doppler_freq * params.num_pulses * params.pulse_rep_interval) +
                      params.num_pulses / 2;

    float angle_rad = target.angle * M_PI / 180.0f;

    // 添加目标回波
    for (int ant = 0; ant < params.num_antennas; ++ant)
    {
        // 计算天线间的相位差
        float ant_phase = 2.0f * M_PI * ant * params.antenna_spacing *
                          std::sin(angle_rad) / params.light_speed *
                          params.carrier_frequency;

        for (int pulse = 0; pulse < params.num_pulses; ++pulse) // -----------------------------------------------------------------------params.num_pulses
        {
            // 计算多普勒相位
            float doppler_phase = 2.0f * M_PI * doppler_freq * pulse * params.pulse_rep_interval;

            // 计算信号幅度 (线性)
            float amplitude = std::sqrt(std::pow(10.0f, target.power / 10.0f));

            // 生成目标信号
            Complex signal = amplitude * std::exp(Complex(0, doppler_phase + ant_phase));

            // 添加到数据中
            if (range_bin >= 0 && range_bin < params.num_samples)
            {
                data[ant][pulse][range_bin] += signal;
            }
        }
    }
}
